
package com.cu;

import nu.pattern.OpenCV;
import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test {

    public static void main(String[] args) {
        OpenCV.loadShared();

        // 加载人脸检测的XML文件
        String cascadeName = "D:\\soft\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_default.xml"; // 或者 "haarcascade_frontalface_default.xml"
        CascadeClassifier faceDetector = new CascadeClassifier(cascadeName);

        // 读取图片
        Mat image = Imgcodecs.imread("D:\\test\\20250923200400_6_361.jpg");
        if (image.empty()) {
            System.out.println("Image not found!");
            return;
        }

        // 执行人脸检测
        MatOfRect faceDetections = new MatOfRect();
        faceDetector.detectMultiScale(image, faceDetections);

        Rect[] faces = faceDetections.toArray();


        System.out.println("Detected " + faces.length + " faces. Performing face swap...");
        for (Rect rect : faces) { // 绘制矩形框并标记人脸位置
            Imgproc.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));
        }
        Mat resultImage = null;
        if (faces.length > 2) {
            // 进行人脸交换
            resultImage = swapFaces(image, faces);
        }else{
            resultImage = image;
        }
//        resultImage = image;


        // 保存结果图片
        Imgcodecs.imwrite("D:\\detected_faces.jpg", resultImage);
        System.out.println("Face swap complete! Result saved to D:\\detected_faces.jpg");
    }

    /**
     * 交换图像中的前两个人脸
     * @param image 原始图像
     * @param faces 检测到的人脸区域
     * @return 人脸交换后的图像
     */
    private static Mat swapFaces(Mat image, Rect[] faces) {
        java.util.Arrays.sort(faces, (a, b) -> {
            int areaA = a.width * a.height;
            int areaB = b.width * b.height;
            return Integer.compare(areaB, areaA); // 从大到小排序
        });
        // 创建结果图像副本
        Mat result = image.clone();


        // 取前两个人脸进行交换（如果检测到更多人脸）
        Rect face1 = faces[0];
        Rect face2 = faces[1];

        // 提取两个人脸区域
        Mat faceRegion1 = new Mat(image, face1);
        Mat faceRegion2 = new Mat(image, face2);

        // 调整人脸大小以匹配目标区域
        Mat resizedFace1 = new Mat();
        Mat resizedFace2 = new Mat();

        Imgproc.resize(faceRegion1, resizedFace2, new Size(face2.width, face2.height));
        Imgproc.resize(faceRegion2, resizedFace1, new Size(face1.width, face1.height));

        // 将交换后的人脸复制到对应位置
        resizedFace1.copyTo(result.submat(face2));
        resizedFace2.copyTo(result.submat(face1));


        // 清理资源
        faceRegion1.release();
        faceRegion2.release();
        resizedFace1.release();
        resizedFace2.release();

        return result;
    }
}
